package com.findyou.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

/**
 * @Title: MapperJavaConfig
 * @Author 贾金博
 * @Package com.findyou.config
 * @description: 持久层配置类: 连接池 sqlSessionFactory Mapper代理对象
 *
 * 方式1：保留外部配置文件
 */

@Configuration // 配置类
@PropertySource("classpath:jdbc.properties") // 读取外部的配置文件
public class DataSourceJavaConfig {

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.driver}")
    private String driver;

    @Bean // 连接池
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }

    // sqlSessionFactory 加入ioc容器里面
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        Resource resource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(resource);
        // 指定配置类文件等信息
        return sqlSessionFactoryBean;
    }


    //mapper 代理对象加入到ioc容器里面
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {

        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.findyou.mapper");
        return mapperScannerConfigurer;
    }
}
